import * as React from "react";
import { MyAxios, IResBody } from "../../../config/http";
import { Button, message } from "antd";
import { WrappedFormUtils } from "antd/lib/form/Form";

interface IProps {
  username: string;
  form: WrappedFormUtils;
}

// 获取验证码的按钮
const VerifyCodeButton: React.FC<IProps> = props => {
  const { username, form } = props;
  const [disabled, setDisabled] = React.useState<boolean>(false);
  const [text, setText] = React.useState<string>("获取验证码");

  return (
    <Button
      disabled={disabled}
      onClick={() => {
        form.validateFields(["username"], (err, values) => {
          if (!err) {
            MyAxios.axios
              .get<any, IResBody>(`user/registe/verify/code/${username}`)
              .then(res => {
                message.info(res.msg);
                // 将按钮禁用
                setDisabled(true);
                //开启定时器
                (function() {
                  let time = res.data;
                  const set = setInterval(function() {
                    time--;
                    setText(time.toString());
                    if (time === 0) {
                      setDisabled(false);
                      setText("获取验证码");
                      // 清除定时器
                      clearInterval(set);
                    }
                  }, 1000);
                })();
              });
          }
        });
      }}
    >
      {text}
    </Button>
  );
};
export default VerifyCodeButton;
